'use client';

import { useToast } from '@/hooks/use-toast';
import { authClient } from '@/lib/auth-client';
import { ORDER_PAY_EXPIRE } from '@/lib/constants';
import { checkUnpaidOrder } from '@/service/actions/order';
import type { Order } from '@/service/type/order';
import { useEffect, useRef, useState } from 'react';

export default function OrderStatus({ order }: { order: Order }) {
  const { data: session } = authClient.useSession();
  const { toast } = useToast();
  const [timeValue, setTimeValue] = useState(0);
  const isChecked = useRef(false);
  const timerRef = useRef<ReturnType<typeof setInterval> | undefined>(
    undefined,
  );

  if (!timerRef.current && timeValue > 0) {
    timerRef.current = setInterval(() => {
      setTimeValue((prev) => {
        if (prev === 1) {
          clearInterval(timerRef.current);
          timerRef.current = undefined;
        }
        return prev - 1;
      });
    }, 1000);
  }

  useEffect(() => {
    if (order.status === 'unpaid' && session?.user.role === 'user') {
      const remainSeconds =
        ORDER_PAY_EXPIRE -
        Math.floor((new Date().getTime() - order.createdAt.getTime()) / 1000);
      if (remainSeconds <= 0 && !isChecked.current) {
        isChecked.current = true;
        checkUnpaidOrder({ orderId: order.id }).then(
          ({ error }) =>
            error &&
            toast({
              title: error.message,
              variant: 'destructive',
            }),
        );
      } else if (
        timeValue === 0 &&
        remainSeconds <= ORDER_PAY_EXPIRE &&
        remainSeconds > 0
      ) {
        setTimeValue(remainSeconds);
      }
    }
  }, [timeValue, order.status, order.createdAt, order.id, toast, session]);

  if (order.status === 'unpaid' && session?.user.role === 'user') {
    const remainTime =
      timeValue >= 60
        ? `${Math.floor(timeValue / 60)} 分钟 ${timeValue % 60} 秒`
        : `${timeValue} 秒`;
    return <div className="text-xl font-bold">支付剩余时间: {remainTime}</div>;
  }

  if (order.status === 'unpaid' && session?.user.role === 'shop')
    return <div className="text-xl font-bold">等待用户支付</div>;

  if (order.status === 'unaccepted')
    return <div className="text-xl font-bold">等待商家接单</div>;

  if (order.status === 'pending')
    return <div className="text-xl font-bold">外卖准备中</div>;

  if (order.status === 'delivering')
    return <div className="text-xl font-bold">外卖配送中</div>;

  if (order.status === 'completed')
    return <div className="text-xl font-bold">订单已完成</div>;

  if (order.status === 'canceled')
    return <div className="text-xl font-bold">订单已取消</div>;

  return null;
}
